const express = require('express');
const utils = require('utility');
const Router = express.Router();

const mysql = require('../db/newDB.js');

function md5Pwd(pwd){
	const salt = 'hongshibao19950508BAO';
	return utils.md5(utils.md5(pwd + salt));
}

Router.post('/login', function(req,res){
	const {user, password} = req.body;
	console.log(user, password);
	mysql.findUserByname(user, md5Pwd(password), function(err, result){
		if (err) {
			return res.json({code: 1,msg: '用户名或者密码错误'});
        }
		if (result.length) {
			res.cookie('userid', result[0].id);
			return res.json({code: 0, data: result[0]});
		} 
		return res.json({code: 1,msg: '用户名不存在或者密码错误'});
	})
})

Router.post('/register', function(req, res){
	const {user, password, type} = req.body;
	mysql.findUserByname(user, md5Pwd(password), function(err, doc){
		if (doc.length) {
			return res.json({code: 1,msg: '用户名重复'});
		}
		
        mysql.register(user, md5Pwd(password), type, function(err, result) {
            if (err) {
				return res.json({code: 1,msg: '后端出错了'});
            }
            mysql.findUserByname(user, md5Pwd(password), function(err, doc){
                res.cookie('userid', doc[0].id);
                return res.json({code: 0, data: doc[0]});
                
            })
        })
	})
})

Router.post('/update', function(req, res){
	const userid = req.cookies.userid;
	if (!userid) {
		return res.json({code: 1})
	}
	const body = req.body;
	mysql.updateUser(userid, body, function(err, result){
		if (err) {
            return res.json({code: 1,msg: '提交信息失败！'});
		}
		if (result) {
			mysql.findUserByid(userid, function(err, doc) {
				return res.json({code: 0, data: doc[0]});
			})
		}
		
	})
})



Router.get('/info',function(req, res){
	const userid = req.cookies.userid;
	if (!userid) {
		return res.json({code: 1});
	}
	mysql.findUserByid(userid, function(err, result){
		if (err) {
			return res.json({code: 1, msg: '后端出错了'});
		}
		return res.json({code: 0,data: result});
	})
})

module.exports = Router;